﻿using System.Web.Mvc;
using EmitMapper;
using PCE.Data;
using PCE.Domain;
using PCE.Mvc.Binders;
using PCE.Mvc.Filters;
using PCE.Mvc.Model;

namespace PCE.Mvc.Controllers
{
	[Authorize]
	public class ProfileController : Controller
	{
		private static readonly ObjectMapperManager MapperManager = ObjectMapperManager.DefaultInstance;
		
		private readonly IRepository<Customer, int> _customerRepository;

		public ProfileController(IRepository<Customer, int> customerRepository)
		{
			_customerRepository = customerRepository;
		}

		[HttpGet]
		[PersistanceRequired]
		public ActionResult Edit([CustomerIdentityBinder] int id)
		{
			var profile = _customerRepository.Get(id);
			
			return View(MapperManager.GetMapper<Customer, ProfileDetails>().Map(profile));
		}

		[HttpPost]
		[PersistanceRequired]
		public ActionResult Edit([CustomerIdentityBinder] int id, ProfileDetails profileDetails)
		{
			if (profileDetails.Password != profileDetails.RepeatedPassword)
				ModelState.AddModelError(string.Empty, "Пароли не совпадают");

			if (!ModelState.IsValid)
				return View(profileDetails);

			var profile = _customerRepository.Get(id);

			profile.Password = profileDetails.Password;
			profile.IsCorporate = profileDetails.IsCorporate;
			profile.CompanyName = profileDetails.CompanyName;
			profile.LegalAddress = profileDetails.LegalAddress;
			profile.PhysicalAddress = profileDetails.PhysicalAddress;
			profile.TIN = profileDetails.TIN;
			profile.BIN = profileDetails.BIN;
			profile.Ownership = profileDetails.Ownership;

			_customerRepository.Save(profile);

			//ModelState.AddModelError(string.Empty, "Не удалось обновить  данные пользователя");

			return View(profileDetails);
		}
	}
}